import {createRouter,createWebHistory,RouteRecordRaw} from 'vue-router'
import { useUserStore } from '../store/user';
import { showDialog } from 'vant';

const routes:Array<RouteRecordRaw>=[
  {
    path:'/home',
    name:'home',
    component:()=>import('../views/home/index.vue')
  },
  {
    path:'/download',
    name:'download',
    component:()=>import('../views/download/index.vue')
  },
  {
    path:'/category',
    name:'category',
    component:()=>import('../views/category/index.vue'),
  },
  {
    path:'/care',
    name:'care',
    component:()=>import('../views/category/components/care.vue')
  },
  {
    path:'/cart',
    name:'cart',
    component:()=>import('../views/category/components/cart.vue')
  },
  
  {
    path:'/charts',
    name:'charts',
    component:()=>import('../views/charts/index.vue')
  },
  /* 搜索页面路由 */
  {
    path:'/search/:kw?',
    name:'search',
    component:()=>import('../views/search/index.vue')
  },
  {
    path:'/listenlist',
    name:'listenlist',
    component:()=>import('../views/listenList/index.vue')
  },
  {
    path:'/login',
    name:'login',
    component:()=>import('../views/login/index.vue')
  },
  {
    path:'/detail/:id',
    name:'detail',
    component:()=>import('../views/detail/index.vue')
  },
  {
    path: '/',
    redirect: '/home'
  }
];

const router= createRouter({
  routes,
  history:createWebHistory(),
  scrollBehavior() {
    return { top: 0, left: 0}
  },
});


// 路由守卫

router.beforeEach(async(to,from,next)=>{
  const userStore=useUserStore();
  let token=userStore.token;
  
  if(token){
    //登录
    if(to.path.includes('login')){
      await showDialog({
        title: '提示',
        message: '您已经登录了哦'
      });
      next(from.path);
    }
    let userInfo=userStore.userInfo;
    if(userInfo){
      next();
    }else{
      //没有用户信息
     try {
     await userStore.getUserInfo();
     next();
     } catch (error) {
      //获取用户信息失败（token过期失效）
      userStore.clearUserInfo();
      next('/login');
     }
    }

  }else{
  //没有登录
  if(to.path.includes('/search')){
    let path=to.path;
    await showDialog({
      title: '提示',
      message: '请先登录哦'
    });
    next(`/login?redirect=${path}`);
    
  }else{
    next();
  }
  }
})




export default router